/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.saashousekeeper.dbpool.creator;

import com.huawei.saashousekeeper.constants.DbPoolEnum;
import com.huawei.saashousekeeper.dbpool.hikari.HikariCpPool;
import com.huawei.saashousekeeper.properties.DataSourceProperty;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import lombok.extern.log4j.Log4j2;

import java.util.Optional;

import javax.sql.DataSource;

/**
 * Hikari数据源创建器
 *
 * @since 2022-07-26
 */
@Log4j2
public class HikariDataSourceCreator implements DataSourceCreator {

    @Override
    public DataSource createDataSource(DataSourceProperty dataSourceProperty) {
        HikariCpPool poolTemplate = (HikariCpPool) dataSourceProperty.getPool(getPoolName());
        HikariConfig config = poolTemplate != null ? poolTemplate : new HikariConfig();
        config.setUsername(dataSourceProperty.getUsername());
        config.setPassword(dataSourceProperty.getPassword());
        config.setJdbcUrl(dataSourceProperty.getUrl());
        Optional.ofNullable(dataSourceProperty.getDriverClassName()).ifPresent(config::setDriverClassName);
        log.warn("Hikari {} create success !", config.getPoolName());
        return new HikariDataSource(config);
    }

    @Override
    public boolean close(DataSource dataSource) {
        if (dataSource == null) {
            return true;
        }
        if (dataSource instanceof HikariDataSource) {
            ((HikariDataSource) dataSource).close();
            return true;

        }
        return false;
    }

    @Override
    public String getPoolName() {
        return DbPoolEnum.POOL_HIKARI.getName();
    }
}
